import router from '@/router/index'
import { asyncRoutes} from '@/router/asyncRoutes'
export function hasPermission(route, menus) {
  if (!route.name) return true

  const check = (menus) => {
    for (const menu of menus) {
      if (menu.name === route.name) return true
      if (menu.children && check(menu.children)) return true
    }
    return false
  }
 console.log(menus)
  return check(menus)
}

export function filterAsyncRoutes(routes, menus) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(tmp, menus)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      res.push(tmp)
    }
  })

  return res
}

export function setupDynamicRoutes(userMenus) {
  const accessRoutes = filterAsyncRoutes(asyncRoutes, userMenus)
  accessRoutes.forEach(route => {
    router.addRoute(route)
  })
}
